import { beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import request from 'supertest'
import app from '../src/index.js'

// 全局测试配置
global.request = request(app)

// 测试数据库配置
process.env.NODE_ENV = 'test'
process.env.JWT_SECRET = 'test-jwt-secret-key-for-testing-only'
process.env.DB_HOST = 'localhost'
process.env.DB_NAME = 'endo_sight_uc_test'
process.env.ENCRYPTION_KEY = 'test-encryption-key-32-chars-long'

// Mock console methods to reduce test output noise
global.console = {
  ...console,
  log: jest.fn(),
  debug: jest.fn(),
  info: jest.fn(),
  warn: jest.fn(),
  error: jest.fn()
}

// 测试用户数据
global.testUser = {
  id: 1,
  username: 'testdoctor',
  password: 'testpass123',
  role: 1,
  name: '测试医生',
  email: 'test@example.com',
  created_at: new Date().toISOString()
}

// JWT Token for testing
global.testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ0ZXN0ZG9jdG9yIiwicm9sZSI6MSwiaWF0IjoxNjMwMDAwMDAwLCJleHAiOjk5OTk5OTk5OTl9.test-token'

// 测试任务数据
global.testTask = {
  id: 1,
  patient_code: 'TEST001',
  clinical_text: '测试临床信息',
  image_path: '/test/path/image.jpg',
  status: 1, // 处理中
  doctor_id: 1,
  created_at: new Date().toISOString()
}

// 测试结果数据
global.testResult = {
  id: 1,
  task_id: 1,
  score: 5,
  severity: 2,
  severity_name: '中度',
  confidence: 0.85,
  created_at: new Date().toISOString()
}

// Before all tests
beforeAll(async () => {
  console.log('🧪 开始后端API测试套件')

  // 等待数据库连接
  await new Promise(resolve => setTimeout(resolve, 1000))
})

// After all tests
afterAll(async () => {
  console.log('✅ 后端API测试套件完成')

  // 清理测试数据
  // 注意：这里应该添加数据库清理逻辑
})

// Before each test
beforeEach(async () => {
  // 每个测试前的准备工作
  // 比如清理mock函数调用记录
  jest.clearAllMocks()
})

// After each test
afterEach(async () => {
  // 每个测试后的清理工作
})

// 测试工具函数
global.testUtils = {
  // 创建测试用户
  async createTestUser(userData = {}) {
    const user = { ...global.testUser, ...userData }
    return user
  },

  // 创建测试任务
  async createTestTask(taskData = {}) {
    const task = { ...global.testTask, ...taskData }
    return task
  },

  // 创建测试结果
  async createTestResult(resultData = {}) {
    const result = { ...global.testResult, ...resultData }
    return result
  },

  // 生成JWT Token
  generateTestToken(payload = {}) {
    const defaultPayload = {
      id: 1,
      username: 'testdoctor',
      role: 1
    }
    return 'mock-jwt-token'
  },

  // 创建测试文件
  createTestFile(filename = 'test.jpg', content = 'test-image-content') {
    return {
      fieldname: 'image',
      originalname: filename,
      encoding: '7bit',
      mimetype: 'image/jpeg',
      size: content.length,
      buffer: Buffer.from(content),
      destination: '/test/uploads',
      filename: filename,
      path: `/test/uploads/${filename}`
    }
  }
}

// 全局错误处理
process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的Promise拒绝:', reason)
})

process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error)
})